<?php
include 'functions.php';

/**
 * Add cropping plan. </br>
 * If the blockid and year exists in the table,
 * update the record. 
 * @param int $blockid 
 * 		It is a blockid from table BLOCK.blockid
 * @param string $year
 * 		It is a 4-digit string
 * @param $plan
 * 		It is a string that represent block info.</br>
 * 		NO MORE THAN 20000 BYTES
 */
function addPlan($blockid, $year, $plan){
	if($blockid == null || $year == null) {
		die("No block or year specified");
	}
	//check if exists
	$con = connect_db();
	$sql = "select * from CROPPING_PLAN
			WHERE blockid = $blockid
			AND year = $year";
	$result = mysql_query($sql, $con) or die(mysql_error());
    
	//exists
	if(count($result) == 1){
		mysql_close($con);
		updatePlan($blockid, $year, $plan);
		return;
	}
	
	//add new record
	$sql = "insert into CROPPING_PLAN 
		(blockid, year, plan) values
		('$blockid', '$year', '$plan')";
	if(mysql_query($sql, $con)){
		echo "add plan success!";
	}else{
		echo "add plan failed!";
	}
	mysql_close($con);
}
/**
 * Update cropping plan.</br>
 * Private function
 * @param int $blockid 
 * 		It is a blockid from table BLOCK.blockid
 * @param string $year
 * 		It is a 4-digit string
 * @param $plan
 * 		It is a string that represents block info.</br>
 * 		NO MORE THAN 20000 BYTES
 */
function updatePlan($blockid, $year, $plan){
	$con = connect_db();
	$sql = "update CROPPING_PLAN
			SET	planstr = '$plan'
			WHERE blockid = $blockid
			AND year = $year";
	if(mysql_query($sql, $con)){
		echo 'update plan ok!';
	}else{
		echo 'update plan failed.';
        die(mysql_error());
	}
	mysql_close($con);
}
/**
 * Get the plan for a block and year.
 * @param int $blockid 
 * 		It is a blockid from table BLOCK.blockid
 * @param string $year
 * 		It is a 4-digit string
 * @return string $plan
 * 		It is a string that represents block info</br>
 * 		NO MORE THAN 20000 BYTES
 */
function getPlan($blockid, $year){
	if($blockid == null || $year == null) {
		die("No block or year specified");
	}
	$con = connect_db();
	$sql = "select * from CROPPING_PLAN
			WHERE blockid = $blockid
			AND year = $year";
	$result = eatResult(mysql_query($sql, $con));
	mysql_close($con);
	return count($result) >= 1 ? $result[0]['planstr'] : null;
}

function getEmptyMap($blockid){
    if($blockid == null){
        die("No block id specified");
    }
    $con = connect_db();
    $sql = "select * from BLOCK where blockid = $blockid";
    $result = eatResult(mysql_query($sql, $con));
    mysql_close($con);
    return count($result) >= 1 ? $result[0]['emptymap'] : null;
}


/**
 * 
 * @param unknown_type $blockid
 * @param tinyint $type
 * 		0 for raised bed, 1 for native soil.
 */
function updateBlockType($blockid, $type){
	if($blockid == null) {
		die("No block specified");
	}
	$con = connect_db();
	$sql = "update BLOCK
			SET	type = $type
			WHERE blockid = $blockid;";
	if(mysql_query($sql, $con)){
		echo 'update block ok!';
	}else{
		echo 'update block failed.';
	}
	mysql_close($con);
}
?>